import { Provide } from '@midwayjs/core';
import { UserCollectEntity } from '../entity/collect';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
import { GoodsInfoEntity } from '../../goods/entity/info';
import { BaseService } from '@cool-midway/core';

@Provide()
export class UserCollectService extends BaseService {
    @InjectEntityModel(UserCollectEntity)
    collectEntity: Repository<UserCollectEntity>;

    @InjectEntityModel(GoodsInfoEntity)
    goodsEntity: Repository<GoodsInfoEntity>;

    /**
     * 收藏或取消收藏商品
     */
    async toggleCollect(userId: number, goodsId: number) {
        // 检查是否已收藏
        const exist = await this.collectEntity.findOne({
            where: { userId, goodsId }
        });

        if (exist) {
            // 如果已收藏，则取消收藏
            await this.collectEntity.delete(exist.id);
            return {
                collect: false,
                message: '已取消收藏'
            };
        }

        // 获取商品信息
        const goods = await this.goodsEntity.findOne({
            where: { id: goodsId }
        });

        if (!goods) {
            throw new Error('商品不存在');
        }

        // 添加收藏
        await this.collectEntity.save({
            userId,
            goodsId
        });

        return {
            collect: true,
            message: '收藏成功'
        };
    }

    /**
     * 获取用户收藏列表
     */
    async getUserCollects(userId: number) {
        return await this.collectEntity
            .createQueryBuilder('collect')
            .leftJoinAndSelect(GoodsInfoEntity, 'goods', 'goods.id = collect.goodsId')
            .where('collect.userId = :userId', { userId })
            .orderBy('collect.createTime', 'DESC')
            .getMany();
    }

    /**
     * 获取用户收藏详情
     */
    async getUserCollectDetail(userId: number, goodsId: number) {
        return await this.collectEntity.findOne({
            where: { userId, goodsId }
        });
    }
} 